<?php

declare(strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

use think\facade\Cache;
use think\facade\Event;
use app\common\controller\Config;


/**
 * @mixin \think\Model
 */
class Relation extends Base
{

    protected $name = 'user_relation';

    public function getAll($param)
    {
        try {

            return $this->where($param)->select()->toArray();
        } catch (\Exception $e) {
            return [];
        }
    }

    protected function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,is_active,level_id,my_total,team_total');
    }

    protected function fresh()
    {
        return $this->hasOne(User::class, 'id', 'new_uid')
            ->field('id,code,photo,nickname,mobile,team_total,level_id');
    }

    /**
     * 原点 2020年8月22日16:25:27 记录推荐关系
     *
     * @param $uid -- 新会员ID
     * @param $code -- 新会员编号
     * @param $status -- 状态：默认0普通会员1正式会员
     * @param $parent_id -- 推荐人的ID
     * @return array
     */
    public function record($uid, $code, $parent_id, $status = 0)
    {
        try {
            $algebra = 1;
            $time = time();
            if ($parent_id) {
                $p_id = $parent_id;
                $insert = [];
                while ($parent = User::where('id', $p_id)->field('id,code,parent_id')->find()) {
                    if ($parent) {
                        $data['uid'] = $parent->id;
                        $data['code'] = $parent->code;
                        $data['new_uid'] = $uid;
                        $data['new_code'] = $code;
                        $data['algebra'] = $algebra;
                        $data['create_time'] = $time;
                        $data['status'] = $status;
                        $insert[] = $data;
                        $p_id = $parent->parent_id;
                    }
                    $algebra++;
                }
                $this->insertAll($insert);
            }
            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队业绩key
     * 原点 2021年12月28日11:50:17 更新团队业绩
     */
    public static function renewTeamTotal($amount, $uid, $key = 'team_total')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        //print_r($all_id);die;
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($amount))->update();
        }
    }
    /**
     * 奖金
     */
    public static function freeBonus($user, $jiangli)
    {

        $sysm = Config::lists();
        try {

            $money = $user->assets->green_integral;
            if ($money <= 0) {
                return ['code' => -1, 'msg' => '绿色积分不足'];
            }
            /**
             * 静态释放奖励
             */
            //return UserRelease::dynamic_release($money,$jiangli,$user,$user->id,'静态释放',1,1);
            UserRelease::dynamic_release($money, $jiangli, $user, $user->id, '静态释放' . ($jiangli * 100) . '%', 1, 1);
            /**
             * 直推奖
             */
            $upuser = User::where('id', $user->parent_id)->find();
            if (!empty($upuser)) {
                $upRelease = UserRelease::where(['status' => 1, 'uid' => $upuser->id])->find();

                if (!empty($upRelease)) {
                    UserRelease::dynamic_release($money, $jiangli, $upuser, $user->id, '直推奖励', $sysm['tp_1'], 2);
                }
                //return $upRelease;
            }
            /**
             * 间推奖
             */
            $twouser = User::where('id', $upuser->parent_id)->find();
            if (!empty($twouser)) {
                $uidcount = parent::where(['uid' => $twouser['id'], 'algebra' => 1])->column('new_uid');
                $countuser = User::whereIn('id', $uidcount)->where('is_active', 2)->count();
                if ($countuser >= $sysm['tp_count']) {
                    $twoRelease = UserRelease::where(['status' => 1, 'uid' => $twouser->id])->find();
                    if (!empty($twoRelease)) {
                        UserRelease::dynamic_release($money, $jiangli, $twouser, $user->id, '间推奖励', $sysm['tp_2'], 3);
                    }
                }
            }
            /**
             * 团队奖
             */
            $teme = parent::where(['new_uid' => $user['id']])->with(['user'])->field('id,uid,algebra')->order('algebra', 'asc')->select();
            $level = 0;

            //return $teme;
            foreach ($teme as $k => $v) {
                $temRelease = UserRelease::where(['status' => 1, 'uid' => $v['uid']])->find();
                if (!empty($temRelease)) {
                    if ($v->user->level_id > $level) {
                        $temeuser = User::where('id', $v['uid'])->find(); //当前用户
                        if ($temeuser->parent_id != 0) {
                            $levelup = Level::where('id', $level)->value('integral'); //上个用户的团队级别比例
                            $nowlevel = Level::where('id', $v->user->level_id)->value('integral'); //当前用户团队级别比例
                            $tp = round(($nowlevel - $levelup), 2); //极差
                            if ($tp > 0) {
                                $ress =  UserRelease::dynamic_release($money, $jiangli, $temeuser, $user->id, '团队奖励', $tp, 5);
                                $temeupuser = User::where('id', $temeuser->parent_id)->find();
                                if ($upuser->id != 1) {
                                    if (!empty($temeupuser) && $temeupuser->level_id == $temeuser->level_id) {
                                        if ($ress['money'] > 0) {
                                            UserRelease::dynamic_release($ress['money'], 1, $temeupuser, $user->id, '平级奖励', $sysm['pingji'], 4);
                                        }
                                    }
                                }
                            }
                            $level = $v->user->level_id;
                        }
                    }
                }
            }

            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * @param $uid
     * @param $total
     * @return array|int[]
     * 原点 2023年7月12日14:16:53 团队奖
     */
    public static function teamBonus($uid, $total, $recoil_count): array
    {
        try {

            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();
            $poor = 0;
            $level_id = 0;
            $expendTotal = 0;
            $flat = 0;
            $flat_open = true;
            $recoil_tp = Cache::get('system')['recoil_tp'];
            //$flat_total = 0;
            foreach ($list as $item) {
                if ($item->user->is_active != 2 || $item->user->is_out) continue;
                //大区加速
                if ($item->user->recoil_count <= 1 && $recoil_count <= 1) {
                    //大区加速
                    $areaAll = User::where('parent_id', $item->uid)->order('team_total', 'desc')
                        ->column('my_total+team_total as team_total,id');
                    $max_speed = Cache::get('system')['max_speed'];
                    if (!empty($areaAll) && $max_speed > 0 && count($areaAll) > 1) {
                        $max = array_shift($areaAll);
                        $ids = Relation::where(['uid' => $max['id']])->column('new_uid');
                        $ids[] = $max['id'];
                        if (in_array($uid, $ids)) {
                            $amount = UserRelease::testingCapping($item->uid, round($total * $max_speed, 2));
                            $recoil = round($amount * $recoil_tp, 2);
                            Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '大市场加速', '+')
                                ->createBonus($uid, 5);
                        }
                    }
                }
                //直推
                if ($item->algebra == 1) {
                    $count = User::where(['is_active' => 2, 'parent_id' => $item->uid])->count();
                    $tp = $count >= 3 ? Cache::get('system')['speed_3'] : Cache::get('system')['speed_' . $count];
                    $amount = UserRelease::testingCapping($item->uid, round($total * $tp, 2));
                    if ($amount > 0) {
                        $expendTotal += $amount;
                        $recoil = round($amount * $recoil_tp, 2);
                        Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '消费分润', '+')
                            ->createBonus($uid, 2);
                    }
                }
                //团队奖
                $level = Level::where('id', $item->user->level_id)->find();
                if (empty($level)) continue;
                if ($item->user->level_id > $level_id && $level->tp > $poor) {
                    $amount = UserRelease::testingCapping($item->uid, round($total * ($level->tp - $poor), 2));
                    if ($amount > 0) {
                        $expendTotal += $amount;

                        $recoil = round($amount * $recoil_tp, 2);
                        Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '培育分润', '+')
                            ->createBonus($uid, 3);
                    }
                    $poor = $level->tp;
                    $level_id = $item->user->level_id;
                    $flat = $item->user->level_id;
                    $flat_open = true;
                    //$flat_total = $amount;
                } else {

                    if ($item->user->level_id == $flat && $flat_open) {
                        $amount = UserRelease::testingCapping($item->uid, round($total * $level->flat_tp, 2));
                        if ($amount > 0) {

                            $recoil = round($amount * $recoil_tp, 2);
                            Target::Account()->basics($item->uid, ['recoil', 'bonus'], [$recoil, $amount - $recoil], '平级奖', '+')
                                ->createBonus($uid, 4);

                            $expendTotal += $amount;
                        }
                        $flat_open = false;
                    }
                }
            }
            if ($expendTotal > 0) {
                Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
            }
            return ['code' => 1];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @param $uid
     * @return array
     * 原点 2023年5月12日17:01:26 升级
     */
    public static function upgrade($uid): array
    {
        try {
            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();

            foreach ($list as $item) {
                $min_total = User::geMinTeam($item->user->id);
                $count = User::where([['parent_id', '=', $item->user->id], ['level_id', '>=', $item->user->level_id]])->count();
                $level = Level::where('id', '>', $item->user->level_id)
                    ->where('zt_count', '<=', $count)
                    ->where('money_count', '<=', $min_total)
                    ->order('id', 'asc')
                    ->find();
                if ($level) {
                    User::update(['level_id' => $level->id, 'id' => $item->uid]);
                }
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 锁仓奖励
     */
    public static function lock_reward($info, $user)
    {
        $sysm = Config::lists();
        $tp_money = 0; //推荐奖励
        $manage_money = 0; //管理奖
        $money = $info->num;
        try {
            $lock = $user->assets->lock;
            // if ($lock <= 0) {
            //     return ['code' => -1, 'msg' => '锁仓账户积分不足'];
            // }
            $lock_money = $money * $sysm['lock_bl'];
            if ($lock_money > $lock) {
                $lock_money = $lock;
            }
            if ($lock_money > 0) {
                Target::Account()->basics($user['id'], 'lock',$lock_money, '交易完成锁仓释放', '-')
                    ->createNormal();
                Target::Account()->basics($user['id'], 'wait', $lock_money, '交易完成锁仓释放', '+')
                    ->createNormal();
                $info->shifang = 1;
                $info->save();
                /**
                 * 推荐奖
                 */
                if ($user->parent_id != 0) {
                    $tp_money = self::check_bonus($user->parent_id, round($lock_money * $sysm['lock_tp'], 2));
                    if ($tp_money > 0) {
                        Target::Account()->basics($user->parent_id, 'sold', $tp_money, '推荐奖', '+')
                            ->createBonus($user->id, 6);
                        Target::Account()->basics($user->parent_id, 'bonus', $tp_money, '推荐奖扣除通证', '-')
                            ->createNormal();
                    }
                }
                /**
                 * 管理奖
                 */
                $list = self::getLevelInfo($user->id);
                if (!empty($list)) {
                    foreach ($list as &$v) {
                        if ($v['bl'] > 0) {
                            $m_money = self::check_bonus($v['uid'], round($v['bl'] * $lock_money, 2));
                            if ($m_money > 0) {
                                Target::Account()->basics($v['uid'], 'sold', $m_money, '管理奖', '+')
                                    ->createBonus($user->id, 7);
                                Target::Account()->basics($v['uid'], 'bonus', $m_money, '管理奖扣除通证', '-')
                                    ->createNormal();
                                $manage_money += $m_money;
                            }
                        }
                    }
                }
            }
            $count_money = round($manage_money + $lock_money, 2);
            if ($count_money > 0) {
                Event::trigger('Statistics', ['key' => 'expend', 'value' => $count_money]);
            }
            return ['code' => 1, 'msg' => '交易完成'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 级差奖励
     */
    public static function getLevelInfo($uid)
    {
        try {
            $level_id = 0;
            $list = parent::where('new_uid', $uid)->with(['user'])->order('algebra asc')->select();
            foreach ($list as $k => $v) {
                if ($v->user->level_id > $level_id && $v->user->level_id <= 8) {
                    $nowmoney = Level::where('id', $v->user->level_id)->value('manage');
                    $upmoney = Level::where('id', $level_id)->value('manage');
                    $data['uid'] = $v->user->id;
                    $data['bl'] = $nowmoney - $upmoney;
                    $ids[] = $data;
                    $level_id = $v->user->level_id;
                }
            }
            if (!empty($ids)) {
                return $ids;
            } else {
                return [];
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 判断通证是否足够
     */
    public static function check_bonus($uid, $num)
    {
        $money = $num;
        $sold = Assets::where(['uid' => $uid])->value('bonus');
        if (($sold - $money) < 0) {
            $money = $sold;
        }
        return $money;
    }
}
